package cn.topevery.garden.dal.dao.impl;

import cn.topevery.garden.dal.dao.IotDeviceIrrigationLogDao;
import cn.topevery.garden.entity.po.IotDeviceIrrigationLog;
import cn.topevery.garden.entity.query.IotDeviceIrrigationLogQuery;
import cn.topevery.garden.entity.vo.IotDeviceIrrigationLogVO;
import cn.topevery.garden.entity.vo.IrrigationInfoVO;
import cn.topevery.garden.framework.base.BaseDaoImpl;
import hw.topevery.framework.db.CommandType;
import hw.topevery.framework.db.entity.DataPager;
import hw.topevery.framework.db.entity.SqlQueryMate;
import hw.topevery.framework.db.enums.ScriptConditionEnum;
import hw.topevery.framework.entity.DbCsp;
import hw.topevery.framework.entity.KeyValue;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author code-generate
 * @date 2021-09-16
 */
@Repository
public class IotDeviceIrrigationLogDaoImpl extends BaseDaoImpl<IotDeviceIrrigationLog> implements IotDeviceIrrigationLogDao {
    @Override
    public <P extends DbCsp> List<IotDeviceIrrigationLog> getSearch(P para) {
        return null;
    }


    @Override
    public DataPager<IotDeviceIrrigationLogVO> listPage(IotDeviceIrrigationLogQuery query) {
        String table = "t_iot_device_irrigation_log tidil";

        String columns = "tidil.*";

        int pageIndex = query.pageIndex - 1;
        int pageSize = query.pageSize;

        SqlQueryMate sqlQueryMate = new SqlQueryMate(table).setColumns(columns).setOrderBy("tidil.c_id desc");
        sqlQueryMate
                .where(true, "tidil.c_db_status", ScriptConditionEnum.Eq, 0)
                .where(StringUtils.isNotBlank(query.getCode()), "tidil.c_device_code", ScriptConditionEnum.Eq, query.getCode())
        ;

        return getDataPager(sqlQueryMate, pageSize, pageIndex, IotDeviceIrrigationLogVO.class);
    }

    @Override
    public IotDeviceIrrigationLog getEntityByColumn(String key, String value) {
        KeyValue<String> map = new KeyValue<>();
        map.key = key;
        map.value = value;
        return getEntityByColumnEqValue(map);
    }

    @Override
    public List<IrrigationInfoVO> getIrrigationInfo() {
        String sql = "select max(t.c_a01097rtd) soil1,max(t.c_a01098rtd) soil2,max(t.c_a01099rtd) soil3, Hour(t.c_date) hour from t_iot_device_irrigation_log t where t.c_date > CURDATE() GROUP BY Hour(t.c_date) having hour % 2 = 0";
        AtomicReference<List<IrrigationInfoVO>> list = new AtomicReference<>(new ArrayList<>());
        run(sql, CommandType.Text, dbCommand -> {
            list.set(dbCommand.executeToList(IrrigationInfoVO.class));
        });
        return list.get();
    }
}
